<template>
  <div>
    <el-button type="primary" @click="generator" class="gen-btn" v-loading.fullscreen.lock="fullscreenLoading">生成</el-button>
    <el-form
      :model="genForm" label-position="right" label-width="130px"
      :inline="true"
      ref="genForm"
      :rules="genFormRules">
      <el-tabs @tab-click="handleTabClick">
        <el-tab-pane label="基本配置">
          <div class="base-box">
            <el-form-item label="表名" prop="tableName">
              <el-input v-model="genForm.tableName" :readonly=true class="gen-input"/>
            </el-form-item>
            <el-form-item label="表说明">
              <el-input v-model="genForm.comment" :readonly=true class="gen-input"/>
            </el-form-item>
            <el-form-item label="实体名称" prop="modelName">
              <el-input v-model="genForm.modelName" class="gen-input" placeholder="表对应的对象名称"/>
            </el-form-item>
            <el-form-item label="模块名称" prop="zhModelName">
              <el-input v-model="genForm.zhModelName" class="gen-input" placeholder="菜单名称"/>
            </el-form-item>
            <el-form-item label="基础包路径" prop="basePackage">
              <el-input v-model="genForm.basePackage" class="gen-input"/>
            </el-form-item>
            <el-form-item label="父菜单">
              <el-input v-model="genForm.parentName" :readonly="true" class="gen-input" placeholder="选择父菜单">
                <el-button @click="openParentDialog" slot="append" icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
            <el-form-item label="选择模板" prop="templateType">
              <el-select v-model="genForm.templateType" placeholder="请选择生成模板" @change="typeChange" class="gen-input">
                <el-option v-for="(item, index) in types.templateType" :key="index" :label="item" :value="item"/>
              </el-select>
            </el-form-item>
            <el-form-item label="数据权限">
              <el-switch v-model="genForm.dataScope" class="gen-input">
              </el-switch>
            </el-form-item>
            <el-form-item v-if="isQueryAll" label="queryAll">
              <el-switch v-model="genForm.queryAll">
              </el-switch>
            </el-form-item>
          </div>
          <div class="relate-box" v-if="isRelate">
            <div>
              关联表配置:
            </div>
            <div class="relate-info">
              <el-form-item label="关联父表的表名" prop="relateTable.tableName">
                <el-input v-model="genForm.relateTable.tableName" placeholder="表名" class="gen-input"/>
              </el-form-item>
              <el-form-item label="父表的实体名称" prop="relateTable.modelName">
                <el-input v-model="genForm.relateTable.modelName" placeholder="表对应的对象名称" class="gen-input"/>
              </el-form-item>
              <div class="replate-field">
                关联字段:
              </div>
              <el-form-item label="父表字段" prop="relateTable.fieldName">
                <el-input v-model="genForm.relateTable.fieldName" placeholder="一般为主键id" class="gen-input"/>
              </el-form-item>
              <el-form-item label="本表字段" prop="relateTable.parentTableField">
                <el-input v-model="genForm.relateTable.parentTableField" placeholder="对应于外键" class="gen-input"/>
              </el-form-item>
            </div>
          </div>
          <div class="set-tips">
            <div class="tips">提示:</div>
            <p v-if="isQueryAll">* queryAll表示是否生成查询单表所有记录的方法, 如果是关联表中的父表, 则需要选择生成</p>
            <p v-if="isRelate">* 请确认父表对应的代码已经生成.</p>
            <p v-if="genForm.dataScope">* 数据权限需要当前表有dept_id字段</p>
          </div>
        </el-tab-pane>
        <el-tab-pane label="字段信息">
          <el-table :data="genForm.columns" stripe
            v-loading="tableLoading"
            element-loading-text="拼命加载中"
            element-loading-spinner="el-icon-loading"
            :span-method="spanRelateRow">
            <el-table-column label="字段信息" header-align="center">
              <el-table-column prop="columnName" label="列名"/>
              <el-table-column prop="comment" label="列说明">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.comment"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="jdbcType" label="列类型"/>
              <el-table-column prop="propertyName" label="属性名称"/>
              <el-table-column prop="propertyShortType" label="属性类型"/>
            </el-table-column>
            <el-table-column label="列表" header-align="center">
              <el-table-column prop="listShow" label="列表" width="50" align="center">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.listShow"></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column prop="query" label="查询" width="50" align="center">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.query"></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column prop="match" label="匹配方式">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.match">
                    <el-option v-for="(item, index) in types.match" :key="index" :label="item" :value="item"/>
                  </el-select>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="表单" header-align="center">
              <el-table-column prop="edit" label="新增/修改" width="100" align="center">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.edit"></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column prop="formElement" label="控件类型">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.formElement">
                    <el-option v-for="(item, index) in types.formElement" :key="index" :label="item" :value="item"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="validType" label="验证模式">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.validType" clearable>
                    <el-option v-for="(item, index) in types.valid" :key="index" :label="item" :value="item"/>
                  </el-select>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column prop="dictType" label="字典类型">
              <template slot-scope="scope">
                <el-select v-model="scope.row.dictType" clearable>
                  <el-option v-for="(item, index) in types.dict" :key="index" :label="item.name" :value="item.code"/>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
          <div class="column-tips">
            <div class="tips">提示:</div>
            <p v-if="isRelate">* 关联表中不要选择id</p>
            <p v-if="isRelate">* 关联表中的`列表项`只会生成第一个column</p>
            <p v-if="genForm.dataScope">* 务必在 `列表` `查询` `新增/修改`项中选择dept_id</p>
            <p v-if="isTree">* 树形结构不会生成查询</p>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <el-dialog title="选择父节点"
        :visible.sync="parentTree.dialogVisible"
        width="20%"
        append-to-body>
        <el-tree
          :data="parentTree.treeData"
          :props="parentTree.defaultProps"
          :highlight-current=true
          :expand-on-click-node=false
          node-key="id"
          ref="parentMenu">
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="parentTree.dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="selectParent">确 定</el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>
import * as gen from '@/api/gen'
import {objIsEmpty} from '@/utils/tool'
import {mapGetters} from 'vuex'

export default {
  name: 'ColunmList',
  data () {
    return {
      isRelate: false,
      isQueryAll: false,
      isTree: false,
      genForm: {
        tableName: '',
        comment: '',
        modelName: '',
        zhModelName: '',
        basePackage: 'com.yangxk.kadmin.web.module.system',
        parentId: '',
        parentName: '',
        templateType: '',
        columns: [],
        relateTable: {
          tableName: '',
          fieldName: '',
          parentTableField: ''
        }
      },
      tableLoading: true,
      types: {
        valid: [],
        match: [],
        formElement: [],
        templateType: [],
        dict: []
      },
      fullscreenLoading: false, // 全屏loading
      parentTree: {
        dialogVisible: false,
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'authName'
        }
      },

      genFormRules: {
        tableName: [{required: true, message: '表名不能为空', trigger: 'blur'}],
        modelName: [{required: true, message: '实体名称不能为空', trigger: 'blur'}],
        zhModelName: [{required: true, message: '模块名称不能为空', trigger: 'blur'}],
        basePackage: [{required: true, message: '基础包路径不能为空', trigger: 'blur'}],
        templateType: [{required: true, message: '请选择生成模板', trigger: 'blur'}],
        relateTable: {
          tableName: [{required: true, message: '关联表名不能为空', trigger: 'blur'}],
          modelName: [{required: true, message: '父表实体名称不能为空', trigger: 'blur'}],
          fieldName: [{required: true, message: '字段不能为空', trigger: 'blur'}],
          parentTableField: [{required: true, message: '字段不能为空', trigger: 'blur'}]
        }
      }
    }
  },
  methods: {
    typeChange (item) {
      item === '关联表' ? this.isRelate = true : this.isRelate = false;
      item === '单表增删改查' ? this.isQueryAll = true : this.isQueryAll = false;
      item === '树形结构' ? this.isTree = true : this.isTree = false;
    },
    handleTabClick (tab, event) {
      if (tab.index === '1') { // 字段信息
        if (this.isRelate && !this.genForm.relateTable.tableName) {
          this.$message.error('请填写关联表名');
          return;
        }
        this.getColumns();
      }
    },
    getColumns () { // 获取当前表的字段信息
      // if (this.genForm.columns.length > 0) {
      //   this.tableLoading = false;
      //   return
      // }
      gen.getColumns(this.genForm.tableName).then(res => {
        let result = [...res.data];
        if (this.isRelate) { // 获取关联表的字段信息
          result.push({'columnName': '关联表字段:', 'relate': 1});
          gen.getColumns(this.genForm.relateTable.tableName).then(res => {
            res.data.forEach((ele) => {
              ele.edit = false;
              ele.listShow = false;
              ele.query = false;
            })
            result.push(...res.data);
            this.genForm.columns = result;
            this.tableLoading = false;
          });
        } else {
          this.genForm.columns = result;
          this.tableLoading = false;
        }
      });
    },
    spanRelateRow ({ row, column, rowIndex, columnIndex }) { // 合并关联表字段前一行(说明行)
      if (row.relate === 1) {
        if (columnIndex === 0) {
          return [1, 12];
        } else {
          return [0, 0];
        }
      }
      // return [0, 0];
    },
    getTypes () {
      if (objIsEmpty(this.valid)) {
        gen.getTypes().then(res => {
          this.types.valid = res.data.valid;
          this.types.match = res.data.match;
          this.types.formElement = res.data.formElement;
          this.types.dict = [...res.data.dict];
          // 模板类型过滤掉报表
          res.data.templateType.forEach(ele => {
            if (ele !== '报表') {
              this.types.templateType.push(ele);
            }
          });
        });
      }
    },
    generator () {
      this.$refs.genForm.validate((valid) => {
        if (!valid) {
          return
        }

        this.fullscreenLoading = true;
        gen.generator(this.genForm).then(res => {
          this.fullscreenLoading = false;
          this.$confirm('生成成功，请重新登录', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          });
        }).catch(() => {
          this.fullscreenLoading = false;
        });
      });
    },
    openParentDialog () {
      if (this.parentTree.treeData.length > 0) {
        this.parentTree.dialogVisible = true;
        return;
      }
      this.parentTree.treeData = [...this.menu];
      this.parentTree.dialogVisible = true;
    },
    selectParent () {
      let parentNode = this.$refs.parentMenu.getCurrentNode();
      if (parentNode) {
        this.genForm.parentId = parentNode.id;
        this.genForm.parentName = parentNode.authName;
      }
      this.parentTree.dialogVisible = false;
    }
  },
  computed: {
    ...mapGetters(['menu'])
  },
  created () {
    this.genForm.tableName = this.$route.params.tableName;
    this.genForm.comment = this.$route.params.comment;
    this.getTypes();
  }
}
</script>

<style lang="scss" scoped>
  .gen-btn {
    margin-bottom: 10px;
  }
  .base-box {
    width: 1000px;
  }
  .gen-input {
    width: 350px;
  }

  .relate-box {
    margin-top: 20px;
    width: 1000px;

    .replate-field{
      font-size: 14px;
      margin-left: 10px;
      margin-bottom: 10px;
    }

    .relate-info {
      margin-top: 20px;
    }
  }
  .set-tips, .column-tips {
    font-size: 12px;
    margin-top: 10px;

    .tips {
      font-weight: bold;
    }
  }

</style>
